<?php
class cmsdream_post extends cmsdream_helper {
	
	public function getPage() {
		$tb = $this->config->TABLE_PREFIX;
		$vars = $GLOBALS['V'];
		$pn = explode('/', $vars['pagename']);
		$pn = $this->db->e($pn[count($pn)-1]);
		$pi = $vars['page_id'];
		unset($vars);		
		
		$fields = array("ID",
						//"post_author AS author",
						//"post_date AS `date`",
						"post_title AS title",
						"post_content AS content",
						"comment_status",
						"post_password AS `password`",
						"comment_count AS `comment`"
		);
		$fields = implode(',',$fields);
		$field1 = $pn!='' ? "post_name = '$pn'" : "ID = $pi";
		$needs = " post_type = 'page' AND post_status = 'publish' AND $field1 ";
		$where = " 1 ";
		
		$post = $this->db->fetch("SELECT $fields FROM {$tb}posts WHERE $where AND $needs LIMIT 1");
		if(!empty($post)) {
			$post->title = htmlspecialchars($post->title);
			$content = $this->format_content($post->content);
			$content = $this->replace_gallery($post->ID, $content);
			$post->content = $content;
			
			$pwd = isset($_POST["password-".$post->ID]) ? trim($_POST["password-".$post->ID]) : "";
			if($post->password!='' && $post->password==$pwd) {
				if(!isset($_SESSION['post_password'][$post->ID])) $_SESSION['post_password'][$post->ID] = array($post->ID => $pwd);
				$post->password = '';
			}
		}
		
		return $post;
	}
	
	public function getAttachment() {
		$tb = $this->config->TABLE_PREFIX;
		$vars = $GLOBALS['V'];
		$a = $this->db->e($vars['attachment']);
		$b = intval($vars['attachment_id']);
		unset($vars);		
		
		$fields = array("ID",
						"post_author AS author",
						"post_date AS `date`",
						"post_title AS title",
						"post_content AS content",
						"comment_status",
						"post_mime_type AS mime_type",
						"post_parent AS `parent`",
						"comment_count AS `comment`"
		);
		$field1 = implode(',',$fields);
		$field2 = $a=="" ? "ID = $b" : "post_name = '$a'";
		$needs = " post_type = 'attachment' AND post_status = 'inherit' AND $field2 ";
		$where = " 1 ";
		$table1 = "(SELECT $field1 FROM {$tb}posts WHERE $where AND $needs LIMIT 1) AS a";
		$table2 = "(SELECT meta_value AS meta,post_id FROM {$tb}postmeta WHERE meta_key = '_wp_attachment_metadata') AS b";
		$table3 = "(SELECT ID,post_title AS ptitle FROM {$tb}posts WHERE post_type = 'post' AND post_status = 'publish') AS c";
		$table4 = "(SELECT meta_value AS `file`,post_id FROM {$tb}postmeta WHERE meta_key = '_wp_attached_file') AS d";
		
		$post = $this->db->fetch("SELECT a.*,c.ptitle,b.meta,d.`file` FROM $table1 LEFT JOIN $table2 ON a.ID = b.post_id LEFT JOIN $table4 ON a.ID = d.post_id LEFT JOIN $table3 ON a.parent = c.ID");
		if(!empty($post)) {
			$post->title = htmlspecialchars($post->title);
			$post->ptitle = htmlspecialchars($post->ptitle);
			$post->time = strtotime($post->date);
			$content = $this->format_content($post->content);
			$content = $this->replace_gallery($post->ID, $content);
			$post->content = $content;
			$post->previous = $this->get_post_previous_and_next($post->ID, 'previous', $post->parent, 'attachment', 'inherit', 'menu_order');
			$post->next = $this->get_post_previous_and_next($post->ID, 'next', $post->parent, 'attachment', 'inherit', 'menu_order');
			if(preg_match('/^([a-z])\:([\d]+)\:\{(.*)\}$/i', $post->meta) || preg_match('/^([a-z])\:([\d]+)\:"stdClass"\:([\d]+)\:\{(.*)\}$/i', $post->meta)) {
				$post->meta = unserialize($post->meta);
			} else {
				$post->meta = $post->meta;
			}
		}
		
		return $post;
	}
	
	public function getPost() {
		$tb = $this->config->TABLE_PREFIX;
		$vars = $GLOBALS['V'];
		$id = intval($vars['p']);
		unset($vars);
		$pwd = isset($_POST["password-$id"]) ? trim($_POST["password-$id"]) : "";		
		
		$fields = array("ID",
						"post_author AS author",
						"post_date AS `date`",
						"post_title AS title",
						"post_content AS content",
						"comment_status",
						//"post_mime_type AS mime_type",
						//"ping_status","to_ping","pinged","post_name","guid",
						"post_password AS `password`",
						//"post_content_filtered",
						//"post_parent AS `parent`",
						"comment_count AS `comment`"
		);
		$fields = implode(',',$fields);
		$needs = " post_type = 'post' AND post_status = 'publish' AND post_parent = 0 AND ID = $id ";
		$where = " 1 ";
		
		$post = $this->db->fetch("SELECT p.*,IFNULL(m.meta_value,0) AS thumbnail FROM (
								SELECT $fields FROM {$tb}posts WHERE $where AND $needs LIMIT 1
							) AS p LEFT JOIN (SELECT post_id, meta_value FROM {$tb}postmeta WHERE meta_key = '_thumbnail_id') AS m ON p.ID = m.post_id");
		if(!empty($post)) {
			$post->title = htmlspecialchars($post->title);
			$post->time = strtotime($post->date);
			$post->thumbnail = $this->get_post_thumbnail($post->ID, $post->thumbnail);
			$content = $this->format_content($post->content);
			$content = $this->replace_gallery($post->ID, $content);
			$post->content = $content;
			$post->previous = $this->get_post_previous_and_next($post->ID, 'previous');
			$post->next = $this->get_post_previous_and_next($post->ID, 'next');
			if($post->password!='' && $post->password==$pwd) {
				if(!isset($_SESSION['post_password'][$post->ID])) $_SESSION['post_password'][$post->ID] = array($post->ID => $pwd);
				$post->password = '';
			}
		}
		
		return $post;
	}
	
	public function addComment() {		
		$Data = new stdClass();
		//防刷新
		//-====
		$rt = isset($_SESSION['cmsdream-refresh-time']) ? intval($_SESSION['cmsdream-refresh-time']) : 0;
		if( (time() - $rt) < $this->config->CREFRESH ){
			$_SESSION['cmsdream-refresh-time'] = time();
			$Data->Message = 'It\'s too fast for your opration.';
			return $Data;
		}
		$_SESSION['cmsdream-refresh-time'] = time();
		
		if($this->setting->default_comment_status != 'open'){
			$Data->Message = 'The comment status is closed.';
			return $Data;
		}
		
		if(empty($_SERVER['HTTP_REFERER'])){
			$Data->Message = 'Params error(unknown.001).';
			return $Data;
		}
		
		$_host = @parse_url($_SERVER['HTTP_REFERER']);
		if($_SERVER['HTTP_HOST'] != $_host['host']) {
			$Data->Message = 'Params error(unknown.002).';
			return $Data;
		}
		
		$pid = intval($_POST['pid']);
		$sid = intval($_POST['submit']);
		if($pid != $sid) {
			$Data->Message = 'Params error.';
			return $Data;
		}
		if($GLOBALS['C']->CV_CODE && $GLOBALS['Q']->is_wap == false) {
			$code = isset($_SESSION['cmsdream-v-code']) ? $_SESSION['cmsdream-v-code'] : '';
			if($code=='' || $_POST['vcode']=='' || strtolower($code) != strtolower($_POST['vcode'])){
				$Data->Message = 'The verify code is error.';
				return $Data;
			}
		}
		
		$tb = $this->config->TABLE_PREFIX;			
		$post = $this->db->fetch("SELECT comment_status FROM {$tb}posts WHERE ID = $pid AND  
						post_type IN('attachment','post','page') AND post_status IN('inherit','publish','private') 
						LIMIT 1");
		if(empty($post) || $post->comment_status != 'open'){
			$Data->Message = 'The post is not exists or this post\'s comment is closed.';
			return $Data;
		}
		unset($post);
		
		$_author = "";
		$_email = "";
		$_url = "";
		$_ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
		$_user_id = intval($_POST['logged_user_id']);
		if($_user_id > 0) {
			$c = $GLOBALS['E'];
			$u = $c->get_author_detail($_user_id);
			if(!empty($u)){
				$_author = $u->display_name;
				$_email = $u->email;
				$_url = $u->url;
			}
		} else {
			$_author = $this->db->e(trim($_POST['username']));
			$_email = $this->db->e(trim($_POST['email']));
			$_url = $this->db->e(trim($_POST['url']));
		}
		
		$_comment = $this->db->e(htmlspecialchars($_POST['comment']));
		$_approved = 1;
		
		$_date = date("Y-m-d H:i:s", time());
		$_parent = intval($_POST['parent']);
		$_parent_comment = $this->db->fetch("SELECT comment_ID FROM {$tb}comments WHERE comment_ID = $_parent LIMIT 1");
		$_parent = empty($_parent_comment) ? 0 : intval($_parent);
		$_agent = $_SERVER['HTTP_USER_AGENT']; $_agent = $this->db->e($_agent);
		
		$fvs = array(
			'comment_ID'=>NULL,'comment_post_ID' => $pid,'comment_author' => $_author,'comment_author_email' => $_email,
			'comment_author_url' => $_url,'comment_author_IP' => $_ip,'comment_date' => $_date,'comment_date_gmt' => $_date,
			'comment_content' => $_comment,'comment_approved' => $_approved,'comment_agent' => $_agent,
			'comment_parent' => $_parent,'user_id' => $_user_id,'comment_type' => '','comment_karma' => 0
		);
		
		$fstr = '';
		$vstr = '';		
		foreach($fvs AS $key => $val){
			$fstr .= '`' . $key . '`,';
			$vstr .= (($val===NULL) ? 'NULL,' : '\'' . $val . '\',');
		}
		$fstr = substr($fstr, 0, -1);
		$vstr = substr($vstr, 0, -1);		
		$this->db->query("INSERT INTO `{$tb}comments`($fstr) VALUES($vstr)");
		$this->db->query("UPDATE `{$tb}posts` SET comment_count = (
							SELECT COUNT(*) FROM `{$tb}comments` 
							WHERE `comment_post_ID` = $pid AND `comment_approved` = '1' AND `comment_parent` = 0
						) WHERE ID = $pid");
		$Data->Message = $this->db->insert_id();
		$Data->List = $this->getComment($pid);		
		return $Data;
	}
	
	public function getComment($pid = 0, $parent = 0, $is_children = true){
		$tb = $this->config->TABLE_PREFIX;
		$pid = $pid > 0 ? $pid : $GLOBALS['V']['p'];
		$pageId = isset($_POST['g']) ? intval($_POST['g']) : 0;
		$pageId = $pageId > 0 ? $pageId : 1;
		$fields = array("comment_ID",
						"comment_author AS author",
						"IF(LENGTH(comment_author_url)=0,'#',comment_author_url) AS url", 			
						"comment_parent",
						"comment_date",
						"comment_content"
		);
		$pp = $this->setting->comments_per_page;
		$fields = implode(',',$fields);
		$where = " comment_approved = '1' AND comment_parent = $parent AND comment_post_ID = $pid ";
		$offset = $pp * ($pageId - 1);
		$limit = $parent == 0 ? " LIMIT $offset, " . $pp . " " : "";
		$order = $parent == 0 ? " DESC " : " ASC ";
		$subcf = "(SELECT COUNT(*) FROM {$tb}comments WHERE comment_parent  = m.comment_ID AND comment_approved = '1' AND comment_post_ID = $pid) AS sub";

		$List = new stdClass;
		$List->PageSize = $pp;
		$List->Total = $parent == 0 ? $this->db->fetch_field("SELECT COUNT(*) FROM {$tb}comments WHERE $where") : 0;
		$List->CurrentPage = $pageId;
		$List->Data = array();
		foreach ($this->db->fetch_all("SELECT $fields,$subcf FROM {$tb}comments AS m WHERE $where ORDER BY comment_date_gmt $order $limit") AS $key => $row) {
			$List->Data[$key] = new stdClass();
			$List->Data[$key]->ID = $row->comment_ID;
			$List->Data[$key]->pid = $parent == 0 ? $row->comment_ID : $row->comment_parent;
			$List->Data[$key]->url = $row->url;
			$List->Data[$key]->author = htmlspecialchars($row->author);
			$List->Data[$key]->time = date("Y-m-d H:i", strtotime($row->comment_date));
			$List->Data[$key]->content = $this->format_content($row->comment_content);
			if($is_children) {
				$List->Data[$key]->children = ($row->sub > 0) ? $this->getComment($pid, $row->comment_ID) : NULL;
			}
		}
		return $parent == 0 ? $List : $List->Data;
	}
		
	public function getList($galleryLimit = 4) {
		$tb = $this->config->TABLE_PREFIX;
		$vars = $GLOBALS['V'];
		$q = $GLOBALS['Q'];
		$List = new stdClass;
		$List->Information = new stdClass();
		$List->Information->ID = NULL;
		$List->Information->type = 'home';
		$List->Information->name = $this->setting->blogname;
		$List->Information->description = $this->setting->blogdescription;
		
		$fields = array("ID",
						"post_author AS author",
						"post_date AS `date`",
						"post_title AS title",
						"post_content AS content",
						"comment_status",
						//"post_mime_type AS mime_type",
						//"ping_status","to_ping","pinged","post_name","guid",
						"post_password AS `password`",
						//"post_content_filtered",
						//"post_parent AS `parent`",
						"comment_count AS `comment`"
		);
		$fields = implode(',',$fields);
		
		$needs = " post_type = 'post' AND post_status = 'publish' ";
		$where = " 1 ";
		if( $q->is_date ) {
			$w1 = $vars['year'] > 0 ? " AND Y = '".$vars['year']."' " : "";
			$w2 = $vars['monthnum'] > 0 ? " AND M = '".$vars['monthnum']."' " : "";
			$w3 = $vars['day'] > 0 ? " AND D = '".$vars['day']."' " : "";
			$where .= " AND ID IN (SELECT ID FROM (
							SELECT ID,YEAR(post_date) AS Y,MONTH(post_date) AS M,DAY(post_date) AS D FROM {$tb}posts WHERE $needs
						) AS M WHERE 1 $w1 $w2 $w3) ";
			$s = "";
			if($vars['year'] > 0)		$s .= $vars['year'];
			if($vars['monthnum'] > 0)	$s .= '-'.$vars['monthnum'];
			if($vars['day'] > 0)		$s .= '-'.$vars['day'];
			$List->Information->type = 'date';
			$List->Information->name = $s;
			$List->Information->ID = $s;
			$List->Information->description = $this->setting->blogname;
		} else if( $q->is_category ){
			if( $vars['category_name']!='' ) {
				$cc = explode('/', $vars['category_name']);
				$slug = $cc[count($cc) - 1];
				$slug = strtolower(urlencode($slug));
				$w = "t.slug = '$slug'";
			} else if( $vars['cat'] > 0 ) {
				$w = "t.term_id = " . $vars['cat'];
			} else {
				$w = "1";
			}			
			$where .= " AND ID IN (SELECT object_id FROM {$tb}term_relationships WHERE term_taxonomy_id IN(
							SELECT x.term_taxonomy_id FROM {$tb}terms AS t 
							LEFT JOIN {$tb}term_taxonomy AS x ON t.term_id = x.term_id 
							WHERE x.taxonomy = 'category' AND $w
						)) ";
			$List->Information = $this->db->fetch("SELECT t.term_id AS ID,t.name FROM {$tb}terms AS t LEFT JOIN {$tb}term_taxonomy AS 
										x ON t.term_id = x.term_id WHERE x.taxonomy = 'category' AND $w");
			$List->Information->name = htmlspecialchars($List->Information->name);
			$List->Information->description = $this->setting->blogname;
			$List->Information->type = 'category';
			
		} else if( $q->is_tag ) {
			if( $vars['tag']!='' ) {
				if(is_numeric($vars['tag']))
					$w = "t.term_id = " . $vars['tag'];
				else
					$w = "t.slug = '".strtolower(urlencode($vars['tag']))."'";
			} else {
				$w = "1";
			}
			$where .= " AND ID IN (SELECT object_id FROM {$tb}term_relationships WHERE term_taxonomy_id IN(
							SELECT x.term_taxonomy_id FROM {$tb}terms AS t 
							LEFT JOIN {$tb}term_taxonomy AS x ON t.term_id = x.term_id 
							WHERE x.taxonomy = 'post_tag' AND $w
						)) ";
			$List->Information = $this->db->fetch("SELECT t.term_id AS ID,t.name FROM {$tb}terms AS t LEFT JOIN {$tb}term_taxonomy AS 
										x ON t.term_id = x.term_id WHERE x.taxonomy = 'post_tag' AND $w");
			$List->Information->name = htmlspecialchars($List->Information->name);
			$List->Information->description = $this->setting->blogname;
			$List->Information->type = 'post_tag';
		} else if( $q->is_search ) {
			$s = trim($vars['s']);
			$where .= " AND (post_title LIKE '%".str_replace("'", "''", $s)."%') ";
			$List->Information->name = htmlspecialchars($vars['s']);
			$List->Information->description = $this->setting->blogname;
		} else if( $q->is_author) {
			if($vars['author_name']!='') {
				$s = trim($vars['author_name']);
				$w = "user_nicename = '".str_replace("'", "''", $s)."'";
			} else if($vars['author']!='') {
				$s = trim($vars['author']);
				$w = "user_nicename = '".str_replace("'", "''", $s)."'";
			} else {
				$w = "1";
			}
			$where .= " AND ID IN (SELECT ID FROM {$tb}posts WHERE post_author IN(SELECT ID FROM {$tb}users WHERE $w))";
			$List->Information->type = 'author';
			$List->Information->name = $s;
			$List->Information->ID = $s;
			$List->Information->description = $this->setting->blogname;
		}
		
		$pageId = intval($vars['paged']) > 0 ? $vars['paged'] : 1;
		$limit = $this->setting->posts_per_page;
		$offset = $limit * ($pageId - 1);
		unset($vars);
		
		$List->Total = $this->db->fetch_field("SELECT COUNT(*) FROM {$tb}posts WHERE $where AND $needs");
		$List->CurrentPage = $pageId;
		$List->Data = array();
		foreach($this->db->fetch_all("SELECT p.*,IFNULL(m.meta_value,0) AS thumbnail FROM (
					SELECT $fields FROM {$tb}posts WHERE $where AND $needs ORDER BY post_date DESC LIMIT $offset, $limit
				) AS p LEFT JOIN (SELECT post_id, meta_value FROM {$tb}postmeta WHERE meta_key = '_thumbnail_id') AS m 
					ON p.ID = m.post_id") AS $key => $row) {
			$List->Data[$row->ID] = $row;
			$List->Data[$row->ID]->title = htmlspecialchars($row->title);
			$List->Data[$row->ID]->time = strtotime($row->date);
			//[gallery order="DESC" columns="4"]
			$content = $this->format_content($row->content);
			$content = $this->replace_gallery($row->ID, $content, $galleryLimit);
			$List->Data[$row->ID]->content = $content;
			//$List->Data[$row->ID]->content = "";
			$List->Data[$row->ID]->thumbnail = $this->get_post_thumbnail($row->ID, $row->thumbnail);
		}
		
		return $List;
	}
	
	public function __construct() {
		$this->db = $GLOBALS['DB'];
		$this->config = $GLOBALS['C'];
		$this->setting = $GLOBALS['S'];
	}
	
	public function __destruct(){
	
	}
	
}

